﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Text;

namespace Twitter
{
    public partial class MainPage : PhoneApplicationPage
    {
        public string UserName { get; set; }
        public string Pass { get; set; }
        public MainPage()
        {
            

            InitializeComponent();

            Search.Visibility = Visibility.Visible;
            SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
        }

        // Get profile info
        private void btnLogin_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UserName = txtUser.Text;
            Pass = txtPassword.Password;

            WebClient twitter = new WebClient() { Credentials = new NetworkCredential { UserName = txtUser.Text, Password = txtPassword.Password } };
            twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
            twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/users/show.xml?screen_name=melaniadanciu"));
        }

        //Xml content
        void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            if (e.Error != null)
                return;


            XElement xmlElement = XElement.Parse(e.Result);

            User meAsUser = new User()
            {
                Name = xmlElement.Element("name").Value,
                Description = xmlElement.Element("description").Value,
                Image = (xmlElement.Element("profile_image_url").Value).Replace("_normal", String.Empty),
                Location = xmlElement.Element("location").Value
            };

            ContentProfile.DataContext = meAsUser;
        }

        private void btnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //TODO
        }

        private void textBlockListTitleTimeline_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);

            WebClient twitterF = new WebClient() { Credentials = new NetworkCredential { UserName = UserName, Password = Pass } };

            twitterF.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName+":"+Pass));
        	twitterF.DownloadStringCompleted+=new System.Net.DownloadStringCompletedEventHandler(twitterF_DownloadStringCompleted);
            
            twitterF.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/friends_timeline.xml"));

            }


        private void twitterF_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;


            XElement xmlElement = XElement.Parse(e.Result);

            lstTimeline.ItemsSource = from tweet in xmlElement.Descendants("status")
                                      select new TweetItem
                                      {
                                          UserName = tweet.Element("user").Element("name").Value,
                                          ImageSource = tweet.Element("user").Element("profile_image_url").Value,
                                          Message = tweet.Element("text").Value,
                                          ID=tweet.Element("id").Value
                                      };
        }

        private void textBlockListTitleTweets_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            GetTweets();
        }

        private void GetTweets()
        {
            WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);

            WebClient twitterU = new WebClient() { Credentials = new NetworkCredential { UserName = UserName, Password = Pass } };

            twitterU.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName + ":" + Pass));
            twitterU.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(twitterU_DownloadStringCompleted);

            twitterU.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml"));
        }

        private void twitterU_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
        	if (e.Error != null)
                return;


            XElement xmlElement = XElement.Parse(e.Result);

            lstMyTweets.ItemsSource = from tweet in xmlElement.Descendants("status")
                                      select new TweetItem
                                      {
                                          UserName = tweet.Element("user").Element("name").Value,
                                          ImageSource = tweet.Element("user").Element("profile_image_url").Value,
                                          Message = tweet.Element("text").Value,
                                          ID = tweet.Element("id").Value
                                      };

            ((WebClient)sender).DownloadStringCompleted -= new System.Net.DownloadStringCompletedEventHandler(twitterU_DownloadStringCompleted);
        }

        //Create Post
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            WebClientHelper helper = new WebClientHelper(null);

            helper.Method = "POST";
            string status = "status="+txtPost.Text;
            helper.SendRequest(new Uri("http://api.twitter.com/1/statuses/update.xml",UriKind.Absolute),status, UserName+":"+Pass);
            helper.RequestCompleted += new EventHandler<RequestCompletedEventArgs>(helper_RequestCompleted);
        }

        void helper_RequestCompleted(object sender, RequestCompletedEventArgs e)
        {
            GetTweets();
        }

        //Delete
        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            WebClientHelper helperDelete = new WebClientHelper(null);

            string id = ((Twitter.TweetItem)(((Grid)(((Button)sender).Parent)).DataContext)).ID;
            helperDelete.Method = "POST";
            helperDelete.SendRequest(new Uri("http://api.twitter.com/1/statuses/destroy/"+id +".xml", UriKind.Absolute),"",UserName+":"+Pass);
            helperDelete.RequestCompleted += new EventHandler<RequestCompletedEventArgs>(helperDelete_RequestCompleted);
        }

        void helperDelete_RequestCompleted(object sender, RequestCompletedEventArgs e)
        {
            GetTweets();

            Dispatcher.BeginInvoke(() => { this.btnSend.Focus(); });
        }

        private void textBlockListTitleFallowing_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        	WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);

            WebClient twitterU = new WebClient() { Credentials = new NetworkCredential { UserName = UserName, Password = Pass } };

            twitterU.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName+":"+Pass));
            twitterU.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(twitterU_DownloadStringCompleted);

            twitterU.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml"));
        }

        private void btnSearch_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string toSearch = txtSearch.Text;
			
			 WebClient twitterSearch = new WebClient() { Credentials = new NetworkCredential { UserName = txtUser.Text, Password = txtPassword.Password } };
            twitterSearch.DownloadStringCompleted +=new System.Net.DownloadStringCompletedEventHandler(twitterSearch_DownloadStringCompleted);
            twitterSearch.DownloadStringAsync(new Uri("http://search.twitter.com/search.atom?q="+ toSearch));
			
			 
			
        }

        private void twitterSearch_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            XElement reader = XElement.Parse(e.Result);

            lstFallowing.ItemsSource = from tweet in reader.Elements("{http://www.w3.org/2005/Atom}entry")
                                      select new TweetItem
                                      {
                                          UserName = tweet.Element("{http://www.w3.org/2005/Atom}author").Element("{http://www.w3.org/2005/Atom}name").Value,
                                          Url=tweet.Element("{http://www.w3.org/2005/Atom}author").Element("{http://www.w3.org/2005/Atom}uri").Value
                                      };
        }

        private void lstFallowing_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
			//AnimateSearch.Begin();
            var item = (TweetItem)lstFallowing.SelectedItem;
            NavigationService.Navigate(new Uri("/WebBrowserDemo.xaml?url=" + item.Url+"&"+ "name=" +item.UserName,
                                               UriKind.Relative));
        }

        private void textBlockListTitleFallowing_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }
    }
}
